﻿using AutoMapper;
using DLL.NET.Commonly.AutoMap;
using DLL.NET.Login.Account.Entity.Map;
using DLL.NET50.DB.Account.ORM.Repository;
using DLL.NET50.DB.Account.ORM.Service;
using DLL.NET50.DB.Account.ORM.UOW;
using DLL.NET50.DB.PIVAS.Entitys.DTO.Map;
using DLL.NET50.DB.PIVAS.ORM.Repository;
using DLL.NET50.DB.PIVAS.ORM.Service;
using DLL.NET50.DB.PIVAS.ORM.UOW;
using LogInModule.ViewModels;
using LogInModule.Views;
using Module.DialogService.ViewModels.Dialogs;
using Module.DialogService.Views.Dialogs;
using Module.DialogService.Views;
using MSDM.Views;
using Prism.Ioc;
using PrismModule.LogInModule.ViewModels;
using PrismModule.LogInModule.Views;
using System.Windows;
using System.Runtime.InteropServices;
using System.Threading;
using System;
using System.Diagnostics;
using DLL.WCL.UserWindow;
using System.Collections.Generic;
using Prism.Services.Dialogs;
using DLL.NET.Login.Account.Entity.DTO;
using DLL.NET50.DB.CRUD;
using DLL.NET70.Infrastructure.Prism;
using DLL.Standard.Infrastructure.Log;
using DLL.NET70.Infrastructure;
using MaterialDesignThemes.Wpf;
using Module.ThemePalette;
using System.Windows.Media;
using LogInModule;
using Module.DialogService;
using Module.MDViews;
using Prism.Modularity;
using Module.AccountManagement;
using DLL.Net60.MotionCtrl.ControlBase;
using Module.Motion.Param.Commonly;
using Module.Motion.Run.Commonly;

using PrismModule.WorkFile;
using DLL.NET.DB.MS.Drugs.CRUD.Repository;
using DLL.NET.DB.MS.Drugs.CRUD.Service;
using DLL.NET50.DB.MS.Drugs.ORM.UOW;
using DLL.NET50.DB.MS.ORM.Repository;
using DLL.NET50.DB.MS.ORM.Service;
using DLL.NET50.DB.MS.ORM.UOW;
using DLL.NET60.DB.MS.Entity.Map;
using PrismModule.EditDrugs;
using PrismModule.MS.DeviceParam;
using Prism.Events;
using DLL.MSDM.Entity.Param;
using DLL.Net70.CanAlyst.CX;
using DLL.Net70.CanAlyst.CX.Vince;
using DLL.Net.MotionCtrl.TMCM_USB.UCard1110;
using DLL.Net.MotionCtrl.TMCM_USB_Base;
using DLL.Net.MotionCtrl.TMCM_USB.Card1110And6110;
using DLL.Net.MotionCtrl.TMCM_USB.USixFlushRobot;
using DLL.Net.MotionCtrl.TMCM_USB.UCard6214;
using DLL.Net.MotionCtrl.TMCM_USB.UCard6110;
using DLL.Net.MotionCtrl.TMCM_USB.UCard1110And6214;
using DLL.Net50.MotionCtrl.Vince.MC_Vsmd1x6Base;
using DLL.Net.MotionCtrl.Vince.MSR4C_VsmdCtrl;
using Module.MSDMMotionShell;
using Module.ExternalDevice;
using DLL.NET.DJ.OneDJ;
using DLL.NET.DJ.OneDJ.ZL;
using DLL.NET.ComPort;
using DLL.NET.DJ.MSDM;
using DLL.NET.DJ.MultyDJs;
using DLL.NET.DJ.OneDJ.SCS;
using DLL.NET50.SerialPort.MCU.LED;
using Module.AutoRun;
using DLL.NET50.DB.MS.AdviceAndDrug.ORM.Service;
using DLL.NET50.DB.MS.AdviceAndDrug.ORM.Repository;
using ClassLibrary.Net60.DB.MS.Recorder.UOW;
using DLL.Net.DB.Recorder.CRUD.Repository;
using DLL.Net.DB.Recorder.CRUD.Service;
using DLL.Net.DB.Recorder.Entities.Map;
using DLL.Net.DB.Recorder.Statistics.CRUD;
using DLL.NET50.DB.MS.PIVASAndDicDrug.ORM;
using DLL.NET70.Infrastructure.Prism.EventAggregator;
using Module.MS.Dialog;
using DLL.FlushRobot.MS.Run;
using Module.BindingInjector;
using DLL.NET.CanAlyst.Vince;
using DLL.NET.CanAlyst;
using DLL.NET.MotionCtrl.VinceCan;

namespace MSDM
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        #region 单实例运行

        /// <summary>
        /// 进程
        /// </summary>
        private Mutex mutex;

        /// <summary>
        /// 检查应用程序是否在进程中已经存在了
        /// </summary>
        private void CheckApplicationMutex()
        {
            bool mutexResult;

            // 第二个参数为 你的工程命名空间名。
            // out 给 ret 为 false 时，表示已有相同实例运行。
            mutex = new Mutex(true, "MSDM", out mutexResult);

            if (!mutexResult)
            {
                // 找到已经在运行的实例句柄(给出你的窗体标题名 “Deamon Club”)
                IntPtr hWndPtr = FindWindow(null, "多工位智能配药机");

                // 还原窗口
                ShowWindow(hWndPtr, SW_RESTORE);

                // 激活窗口
                SetForegroundWindow(hWndPtr);

                // 退出当前实例程序
                Environment.Exit(0);
            }
        }

        #region Windows API

        // ShowWindow 参数
        public const int SW_RESTORE = 9;

        /// <summary>
        /// 在桌面窗口列表中寻找与指定条件相符的第一个窗口。
        /// </summary>
        /// <param name="lpClassName">指向指定窗口的类名。如果 lpClassName 是 NULL，所有类名匹配。</param>
        /// <param name="lpWindowName">指向指定窗口名称(窗口的标题）。如果 lpWindowName 是 NULL，所有windows命名匹配。</param>
        /// <returns>返回指定窗口句柄</returns>
        [DllImport("USER32.DLL", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        /// <summary>
        /// 将窗口还原,可从最小化还原
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="nCmdShow"></param>
        /// <returns></returns>
        [DllImport("USER32.DLL")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        /// <summary>
        /// 激活指定窗口
        /// </summary>
        /// <param name="hWnd">指定窗口句柄</param>
        /// <returns></returns>
        [DllImport("USER32.DLL")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        #endregion Windows API

        #endregion 单实例运行

        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        public static Dictionary<string, object> Dic = new Dictionary<string, object>();

        protected override void OnStartup(StartupEventArgs e)
        {
            CheckApplicationMutex();
            Thread t = new Thread(() =>
            {
                SplashWindow sw = new SplashWindow();
                sw.WindowStartupLocation = WindowStartupLocation.Manual;
                double swidth = sw.Width;
                double cwidth = SystemParameters.WorkArea.Width;//得到屏幕工作区域宽度
                double left = (cwidth - swidth) / 2;
                sw.Left = left;
                sw.Top = 300;
                Dic["SplashWindow"] = sw;//储存
                sw.ShowDialog();//不能用Show
            });
            t.SetApartmentState(ApartmentState.STA);//设置单线程
            t.Start();

            Process thisProc = Process.GetCurrentProcess();
            if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
            {
                Application.Current.Shutdown();
                return;
            }
            base.OnStartup(e);
        }

        protected override void OnInitialized()
        {
            SetTheme();
            if (App.Dic.ContainsKey("SplashWindow"))
            {
                SplashWindow sw = App.Dic["SplashWindow"] as SplashWindow;
                sw.Dispatcher.Invoke((Action)(() => sw.Close()));//在sw的线程上关闭SplashWindow
                App.Dic.Remove("SplashWindow");
            }
            var dialog = Container.Resolve<IDialogService>();
            dialog.ShowDialog("Dialog_LogIn", null, callback =>
            {
                if (callback.Result != ButtonResult.OK)
                {
                    Environment.Exit(0);
                    App.Current.Shutdown();
                    return;
                }
                //给主窗体传值
                base.OnInitialized();
            }, nameof(CustomDialogWindow));//, nameof(CustomDialogWindow)
        }

        private static adi_accountDTO logAccount = new adi_accountDTO();

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            RegisterGlobal(containerRegistry);
            RegisiterDialog(containerRegistry);
            RegisterAccount(containerRegistry);
            RegisterMotionCtrl(containerRegistry);
            RegisterPIVAS(containerRegistry);
            RegisterMSRecord(containerRegistry);
            RegisterMSDB(containerRegistry);
            RegisterMSDrug(containerRegistry);
            RegisterDJ(containerRegistry);
            RegisterMS(containerRegistry);
        }

        private IMapper GetMapper(IContainerProvider container)
        {
            var provider = container.Resolve<IAutoMapperProvider>();
            return provider.GetMapper();
        }

        private void RegisterGlobal(IContainerRegistry containerRegistry)
        {
            //注册全局命令
            containerRegistry.RegisterInstance<adi_accountDTO>(logAccount);
            containerRegistry.RegisterSingleton<IApplicationCommands, ApplicationCommands>();

            //注册AutoMapper
            containerRegistry.Register<IUnitOfWork, UnitOfWork>();
            containerRegistry.Register<IAutoMapperProvider, AutoMapperProvider>();
            containerRegistry.Register(typeof(IMapper), GetMapper);

            containerRegistry.RegisterSingleton<ILogHelper, CLogHelper>();
        }

        private void RegisterAccount(IContainerRegistry containerRegistry)
        {
            #region account_management 数据库工作单元

            containerRegistry.RegisterSingleton<IAccountUnitOfWork, CAccountUnitOfWork>();

            #endregion account_management 数据库工作单元

            #region account_management 数据库仓储和服务IAccountService

            containerRegistry.Register<IAccountRepository, CAccountRepository>();
            containerRegistry.Register<IAccountService, CAccountService>();
            containerRegistry.Register<IAccountProfile, CAccountProfile>();

            #endregion account_management 数据库仓储和服务IAccountService
        }

        private void RegisterMotionCtrl(IContainerRegistry containerRegistry)
        {
            RegisterTMCM(containerRegistry);
            RegisterVince_VSMD(containerRegistry);
            RegisterRJCX(containerRegistry);
            RegisterVinceCan(containerRegistry);
            InitializeCard(containerRegistry);
        }

        private void RegisterRJCX(IContainerRegistry containerRegistry)
        {
            containerRegistry.Register<IRJ_CX_CanAlystBase, CRJ_CX_CanAlystBase>();
            containerRegistry.Register<IRJ_CX_CanAlyst, CRJ_CX_CanAlyst>();
            containerRegistry.Register<IRJ_Vince_CXCanAlystBase, CRJ_Vince_CXCanAlystBase>();
            containerRegistry.Register<IRJ_VinceCtrl_CX, CRJ_VinceCtrlBase_CX>();
        }

        private void RegisterVinceCan(IContainerRegistry containerRegistry)
        {
            containerRegistry.Register<ICanBase, CanBase>();
            containerRegistry.Register<ICanBase_Tiny, CanBase_Tiny>();
            containerRegistry.Register<ICanBase_ZHCX, CanBase_ZHCX>();
            containerRegistry.RegisterSingleton<ICanBase, CanBase_Tiny>();

            containerRegistry.Register<IRJ_VinceCanBase, CRJ_VinceCanBase>();
            containerRegistry.Register<IRJ_VinceCanCtrl, CRJ_VinceCanCtrl>();

            containerRegistry.Register<IMC_VinceCan, CMC_VinceCan>();
        }

        private void RegisterTMCM(IContainerRegistry containerRegistry)
        {
            containerRegistry.Register<ITMCM_USB_Base, CTMCM_USB_Base>();
            containerRegistry.Register<IUCard1110, CUCard1110>();
            containerRegistry.Register<IUCard6214, CUCard6214>();
            containerRegistry.Register<IUCard6110, CUCard6110>();

            containerRegistry.Register<IUCard1110And6110, CUCard1110And6110>();
            containerRegistry.Register<IUCard1110And6214, CUCard1110And6214>();
            containerRegistry.Register<IUSixFlushRobot2, CUSixFlushRobot2>();
            containerRegistry.Register<IUSixFlushRobot, CUSixFlushRobot>();
        }

        private void RegisterVince_VSMD(IContainerRegistry containerRegistry)
        {
            containerRegistry.Register<IMC_Vsmd1x6Base, CMC_Vsmd1x6Base>();
        }

        private void InitializeCard(IContainerRegistry containerRegistry)
        {
            CWR_MotionCardType wrcard = new CWR_MotionCardType();
            CMotionCardType card = new CMotionCardType();
            wrcard.ReadParam();
            card = wrcard.Obj;
            switch (wrcard.Obj.DeviceType)
            {
                case 0:
                    {
                        if (wrcard.Obj.MotionCardType == 0)
                        {
                            containerRegistry.RegisterSingleton<IMotionCtrlBase, CUSixFlushRobot>();
                        }
                        else if (wrcard.Obj.MotionCardType == 1)
                        {
                            containerRegistry.RegisterSingleton<IMotionCtrlBase, CUSixFlushRobot2>();
                        }
                        break;
                    }
                case 1:
                    {
                        //四工位配药机器人，vince 控制卡
                        if (wrcard.Obj.MotionCardType == 0)
                        {
                            containerRegistry.RegisterSingleton<IMotionCtrlBase, CMSR4C_VsmdCtrl>();
                        }
                        else if (wrcard.Obj.MotionCardType == 1)
                        {
                            containerRegistry.RegisterSingleton<IMotionCtrlBase, CMC_VinceCan_MSR4C>();
                        }

                        break;
                    }

                default:
                    {
                        containerRegistry.RegisterSingleton<IMotionCtrlBase, CMotionCtrlBase>();
                        break;
                    }
            }
        }

        private void RegisiterDialog(IContainerRegistry containerRegistry)
        {
            //注册对话框
            containerRegistry.RegisterDialog<Dialog_AccountAuthorization, Dialog_AccountAuthorizationViewModel>();
            containerRegistry.RegisterDialog<Dialog_LogIn, Dialog_LogInViewModel>();

            containerRegistry.RegisterDialog<LogIn, LogInViewModel>();
            containerRegistry.RegisterDialog<AlertDialog, AlertDialogViewModel>();
            containerRegistry.RegisterDialog<SuccessDialog, SuccessDialogViewModel>();
            containerRegistry.RegisterDialog<WarningDialog, WarningDialogViewModel>();

            containerRegistry.RegisterDialogWindow<CustomDialogWindow>(nameof(CustomDialogWindow));
            containerRegistry.RegisterDialogWindow<PW_GeneraDialog>(nameof(PW_GeneraDialog));
            ////PUC_AddDrugDialog
            //containerRegistry.RegisterDialog<PUC_DialogEditDrug, PUC_DialogEditDrugViewModel>();
            //containerRegistry.RegisterDialog<Dialog_EditAPBottle, Dialog_EditAPBottleViewModel>();
        }

        private void RegisterPIVAS(IContainerRegistry containerRegistry)
        {
            //Ipivas_read_drugsProfile
            containerRegistry.Register<Ipivas_read_drugsProfile, Cpivas_read_drugsProfile>();
            containerRegistry.Register<Ipivas_read_accountProfile, Cpivas_read_accountProfile>();

            #region pivas drugs

            containerRegistry.Register<IPivasUOW, CPivasUOW>();
            //员工信息表
            containerRegistry.Register<IPivasAccountRepository, CPivasAccountRepository>();
            containerRegistry.RegisterSingleton<IPivasAccountService, CPivasAccountService>();
            //药品字典表
            containerRegistry.Register<IPivasDrugsRepository, CPivasDrugsRepository>();
            containerRegistry.RegisterSingleton<IPivasDrugsService, CPivasDrugsService>();

            #endregion pivas drugs

            #region 医嘱

            containerRegistry.RegisterSingleton<IAdviceDrugService, CAdviceDrugService>();
            containerRegistry.Register<IAdviceDrugRepository, CAdviceDrugRepository>();

            containerRegistry.RegisterSingleton<IAdviceExecuteService, CAdviceExecuteService>();
            containerRegistry.Register<IAdviceExecuteRepository, CAdviceExecuteRepository>();

            #endregion 医嘱
        }

        private void RegisterMSRecord(IContainerRegistry containerRegistry)
        {
            #region recorder

            containerRegistry.Register<IAdviceFlushProfile, CAdviceFlushProfile>();

            //注册UOW
            containerRegistry.Register<IUnitOfWork, UnitOfWork>();
            containerRegistry.Register<IMSRecorderUnitOfWork, CMSRecorderUnitOfWork>();
            //注册仓储
            containerRegistry.Register<IRAdviceDrugRepository, CRAdviceDrugRepository>();
            containerRegistry.Register<IRAdviceExecuteRepository, CRAdviceExecuteRepository>();
            containerRegistry.Register<IRAdviceFlushRepository, CRAdviceFlushRepository>();
            containerRegistry.Register<IRecorderRepositoryManager, CRecorderRepositoryManager>();

            //服务
            containerRegistry.Register<IRAdviceDrugService, CRAdviceDrugService>();
            containerRegistry.Register<IRAdviceExecuteService, CRAdviceExecuteService>();
            containerRegistry.Register<IRAdviceFlushService, CRAdviceFlushService>();
            containerRegistry.Register<IRecorderServiceManager, CRecorderServiceManager>();
            //日志业务逻辑
            containerRegistry.Register<IRecorderStatistics, CRecorderStatistics>();
            containerRegistry.RegisterSingleton<IAdviceRecordService, CAdviceRecordService>();

            #endregion recorder
        }

        private void RegisterMS(IContainerRegistry containerRegistry)
        {
            containerRegistry.Register<IScanBarBase, CScanBarBase>();
            containerRegistry.Register<IMS_ScanBar, CMS_ScanBar>();
            containerRegistry.Register<IPIVASAndDicDrug, CPIVASAndDicDrug>();
            containerRegistry.Register<ISendLogMessage, CSendLogMessage>();
            containerRegistry.Register<ISendCommandMessage, CSendCommandMessage>();
            containerRegistry.Register<IMSDMSendCommandMessage, CMSDMSendCommandMessag>();

            containerRegistry.Register<IMS_HP_RunBase, CMS_HP_RunBase>();
            containerRegistry.RegisterSingleton<IMS_HP_AutoFlush, CMS_HP_AutoFlush>();
        }

        private void RegisterMSDB(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<Iadi_dic_drugProfile, Cadi_dic_drugProfile>();
            //ms_robot uinit of work
            containerRegistry.RegisterSingleton<IMSUnitOfWork, CMSUnitOfWork>();

            //adi_work_file server
            containerRegistry.Register<IWorkFileRepository, CWorkFileRepository>();
            containerRegistry.RegisterSingleton<IWorkFileService, CWorkFileService>();

            #region advice and drugs

            containerRegistry.Register<IAdviceAndDicDrugsRepository, CAdviceAndDicDrugsRepository>();
            containerRegistry.RegisterSingleton<IAdviceAndDicDrugsService, CAdviceAndDicDrugsService>();

            #endregion advice and drugs
        }

        private void RegisterMSDrug(IContainerRegistry containerRegistry)
        {
            #region used drug service

            //ms_robot used drugs database
            containerRegistry.RegisterSingleton<IMSDrugsUOW, CMSDrugsUOW>();

            //locoal back up used drugs database
            containerRegistry.RegisterSingleton<ILocalDrugsUOW, CLocalDrugsUOW>();

            containerRegistry.Register<IBaseDrugsRepository, CBaseDrugsRepository>();
            containerRegistry.Register<IBaseDrugsService, CBaseDrugsService>();

            containerRegistry.Register<IMSDrugsRepository, CMSDrugsRepository>();
            containerRegistry.Register<IMSDrugsService, CMSDrugsService>();
            //
            containerRegistry.Register<ILocalDrugsRepository, CLocalDrugsRepository>();
            containerRegistry.Register<ILocalDrugsService, CLocalDrugsService>();
            //
            //containerRegistry.Register<IServerDrugsRepository, CServerDrugsRepository>();
            //containerRegistry.Register<IServerDrugsService, CServerDrugsService>();
            ////
            //containerRegistry.Register<ICopyDrugsRepository, CCopyDrugsRepository>();
            //containerRegistry.Register<ICopyDrugsService, CCopyDrugsService>();

            containerRegistry.Register<IMSUpOrDownDrugRepository, CMSUpOrDownDrugRepository>();
            containerRegistry.Register<IMSUpAndDownDrugService, CMSUpAndDownDrugService>();

            #endregion used drug service
        }

        private void RegisterDJ(IContainerRegistry containerRegistry)
        {
            containerRegistry.Register<ISerialPortManager, CSerialPortManager>();
            //containerRegistry.Register<ISerialPortManagerFS, CSerialPortManagerFS>();
            //containerRegistry.Register<ISerialPortManagerZL, CSerialPortManagerZL>();
            //containerRegistry.Register<ISerialPortManagerSCS, CSerialPortManagerSCS>();

            //单个舵机
            //containerRegistry.Register<IDJCtrlOne, CDJCtrlOne>();
            containerRegistry.Register<IDJCtrlOneSCSCL, CDJCtrlOneSCSCL>();
            //多个舵机
            containerRegistry.Register<IMultyDjCtrl, CMultyDjCtrl>();

            //多工位配药机下使用的舵机
            containerRegistry.RegisterSingleton<IDJ_MS, CDJ_MS>();

            //ISerialPortManagerMCULED//
            //containerRegistry.Register<ISerialPortManagerMCULED, CSerialPortManagerMCULED>();
            //IControlLED
            containerRegistry.RegisterSingleton<IControlLED, CControlLED>();

            CWR_MotionCardType wrcard = new CWR_MotionCardType();
            CMotionCardType card = new CMotionCardType();
            wrcard.ReadParam();
            card = wrcard.Obj;
            switch (card.DjType)
            {
                case 0:
                    {
                        containerRegistry.Register<IDJCtrlOne, CDJCtrlOneZL>();
                        break;
                    }

                default:
                    {
                        containerRegistry.Register<IDJCtrlOne, CDJCtrlOneZL>();
                        break;
                    }
            }
        }

        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            moduleCatalog.AddModule<ThemePaletteModule>();
            moduleCatalog.AddModule<MDViewsModule>();
            moduleCatalog.AddModule<LogInModuleModule>();
            //AccountManagementModule
            moduleCatalog.AddModule<AccountManagementModule>();
            // moduleCatalog.AddModule<MotionModule>();
            moduleCatalog.AddModule<DialogServiceModule>();

            moduleCatalog.AddModule<ParamCommonlyModule>();
            moduleCatalog.AddModule<RunCommonlyModule>();
            moduleCatalog.AddModule<WorkFileModule>();
            moduleCatalog.AddModule<EditDrugsModule>();
            //Motion control

            //AutoRunModule
            moduleCatalog.AddModule<MSDMMotionShellModule>();
            //////DeviceParamShellModule
            moduleCatalog.AddModule<DeviceParamModule>();
            moduleCatalog.AddModule<ExternalDeviceModule>();
            moduleCatalog.AddModule<AutoRunModule>();
            moduleCatalog.AddModule<DialogModule>();
            moduleCatalog.AddModule<BindingInjectorModule>();
            //EditBottleModule
            //moduleCatalog.AddModule<DialogModule>();
            //MSDMMotionShellModule
        }

        #region SET THEMEN

        private void SetTheme()
        {
            SetThemeFromAppConfig();
        }

        private void SetThemeFromAppSetting()
        {
            App app = (App)Application.Current;
            var paletteHelper = new PaletteHelper();
            var theme = paletteHelper.GetTheme();
            var InitialTheme = Settings_Theme.Default.Theme;

            switch (InitialTheme)
            {
                case BaseTheme.Dark:
                    ModifyTheme(true);
                    break;

                case BaseTheme.Light:
                    ModifyTheme(false);
                    break;
            }

            Color _primaryColor = Settings_Theme.Default.PrimaryColor;

            ModifyTheme(theme => theme.SetPrimaryColor(_primaryColor));

            Color _secondaryColor = Settings_Theme.Default.SecondaryColor;

            ModifyTheme(theme => theme.SetSecondaryColor(_secondaryColor));
        }

        private void SetThemeFromAppConfig()
        {
            App app = (App)Application.Current;
            var paletteHelper = new PaletteHelper();
            var theme = paletteHelper.GetTheme();

            bool isDark = Convert.ToBoolean(AppSetting.Read("BaseTheme"));
            ModifyTheme(isDark);
            string pcs = AppSetting.Read("PrimaryColor");
            if (pcs != null)
            {
                Color pcolor = (Color)ColorConverter.ConvertFromString(pcs);
                ModifyTheme(theme => theme.SetPrimaryColor(pcolor));
            }

            string scs = AppSetting.Read("SecondaryColor");
            if (scs != null)
            {
                Color scolor = (Color)ColorConverter.ConvertFromString(scs);
                ModifyTheme(theme => theme.SetSecondaryColor(scolor));
            }
        }

        private static void ModifyTheme(bool isDarkTheme)
        {
            var paletteHelper = new PaletteHelper();
            var theme = paletteHelper.GetTheme();

            theme.SetBaseTheme(isDarkTheme ? BaseTheme.Dark : BaseTheme.Light);
            paletteHelper.SetTheme(theme);
        }

        private static void ModifyTheme(Action<Theme> modificationAction)
        {
            var paletteHelper = new PaletteHelper();
            Theme theme = paletteHelper.GetTheme();

            modificationAction?.Invoke(theme);

            paletteHelper.SetTheme(theme);
        }

        #endregion SET THEMEN
    }
}